package com.wf.demo.info.exception;


import javax.servlet.http.HttpServletRequest;

import com.wf.demo.info.util.Result;
import com.wf.demo.sys.constant.CommonConstant;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@ControllerAdvice
public class GloabalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /*异常处理，主要是在处理删除父类信息的时候，因为外键约束的存在，而导致违反约束。*/
    @ExceptionHandler(value = Exception.class)
    public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        e.printStackTrace();
        Class constraintViolationException = Class.forName("org.hibernate.exception.ConstraintViolationException");
        if(null!=e.getCause()  && constraintViolationException==e.getCause().getClass()) {
            return Result.error(-1,"违反了约束，多半是外键约束");
        }
        return e.getMessage();
    }

    @ResponseBody
    @ExceptionHandler(AuthenticationException.class)
    public Result handleAuthenticationException(AuthenticationException e){
        logger.error(e.getMessage(), e);
        return Result.error(CommonConstant.User_No_Authentication,"请先登录");  //-3
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        logger.error(e.getMessage(), e);
        return Result.error(-5,"数据库中已存在该记录");
    }
    @ResponseBody
    @ExceptionHandler(AuthorizationException.class)
    public Result handleAuthorizationException(AuthorizationException e){
        logger.error(e.getMessage(), e);
        return Result.error(CommonConstant.User_No_Authorization,"没有权限，请联系管理员授权"); //-4
    }
    @ResponseBody
    @ExceptionHandler(UnauthorizedException.class)
    public Result handleUnauthorizedException(UnauthorizedException e){
        logger.error(e.getMessage(), e);
        return Result.error(CommonConstant.User_No_Authorization,"没有权限，请联系管理员授权");
    }
}
